/**
 *  页面list通用hook
 * @param param0 { toast, loadmoreState, queryFn, query } toast: 提示信息，loadmoreState: 更多加载状态，loading:请求状态，queryFn: 查询函数，query: 查询参数
 * @returns
 */
export const usePageList = ({ toast, queryFn, query, complete }: any) => {
  const total = ref(0)
  const list: any = ref([])
  const queryParams: any = reactive({
    pageNo: 1,
    pageSize: 10
  })
  const loadmoreState: any = ref('loading')
  const loading = ref(false)
  const getList = async (isInit = false) => {
    if (isInit) {
      queryParams.pageNo = 1
    }
    try {
      loading.value = true
      const data: any = await queryFn({ ...queryParams, ...(query?.value || query) })
      const dataList = data.list || (data && Array.isArray(data) ? data : []) || []
      const dataTotal = data.total || dataList.length || 0
      if (queryParams.pageNo > 1) {
        list.value = list.value.concat(dataList)
      } else {
        list.value = dataList
      }
      total.value = dataTotal
      if (list.value.length < total.value) {
        loadmoreState.value = 'loading'
      } else {
        loadmoreState.value = 'finished'
      }
    } catch (error) {
      console.log(error)

      toast.warning(error)
      loadmoreState.value = 'error'
    } finally {
      // 请求完成回调
      complete?.()
      loading.value = false
    }
  }
  // 触底加载
  const handleReachBottom = () => {
    if (list.value.length < total.value) {
      loadmoreState.value = 'loading'
      queryParams.pageNo++
      getList()
    } else {
      loadmoreState.value = 'finished'
    }
  }
  return {
    list,
    total,
    queryParams,
    loadmoreState,
    loading,
    getList,
    handleReachBottom
  }
}
